package cn.yunhe.shiro_demo.config;

import cn.yunhe.shiro_demo.dao.UserMapper;
import cn.yunhe.shiro_demo.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;

public class Realm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user= (User) principalCollection.getPrimaryPrincipal();
        String name=user.getUsername();
        Set<String> roles=userMapper.getRoles(name);
        Set<String> perms=userMapper.getPerms(name);
        SimpleAuthorizationInfo auth=new SimpleAuthorizationInfo();
        auth.addStringPermissions(perms);
        auth.addRoles(roles);
        return auth;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //用户名密码令牌
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //获取用户登录的用户名
        String name = token.getUsername();
        User user=userMapper.getUserByName(name);

        SimpleAuthenticationInfo auth=new SimpleAuthenticationInfo(
                user,user.getPassword(),getName()
        );
        return auth;
    }
}
